/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Evaluacion_View_Add.java
 *
 * Created on 18-sep-2012, 21:33:20
 */
package v;

import beans.DiscapacidadTratamiento;
import beans.EvolucionMedicamento;
import beans.EvolucionTerapia;
import beans.MedicamentoDiscapacidad;
import beans.TerapiaDiscapacidad;
import beans.Tratamiento;
import beans.dao.CitaDAO;
import beans.dao.DiscapacidadTratamientoDAO;
import beans.dao.EvolucionMedicamentoDAO;
import beans.dao.EvolucionTerapiaDAO;
import beans.dao.MedicamentoDiscapacidadDAO;
import beans.dao.TerapiaDiscapacidadDAO;
import beans.dao.TratamientoDAO;
import core.constructor.constructor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.DefaultListModel;
import javax.swing.JFormattedTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import tools.DatosComboBox;

/**
 *
 * @author nowxue
 */
public class Evaluacion_View_Add extends javax.swing.JPanel {

    private Tratamiento tratamiento;
    private Integer idPaciente;
    
    private DefaultListModel discModel = new DefaultListModel();
    
    private String[] columnTerapia = {"Id","Terapia", "Intensidad", "Cantidad", "Inicio"};
    private String[] columnMedic = {"Id","Medicamento", "Dosis", "Uso", "Inicio"};
    
    private DatosComboBox cbx = new DatosComboBox();
    
    private Map<Integer, TerapiaDiscapacidad> mapTerapias = 
            new HashMap<Integer, TerapiaDiscapacidad>();
    
    private Map<Integer, MedicamentoDiscapacidad> mapMedicamentos =
            new HashMap<Integer, MedicamentoDiscapacidad>();
    
    private TableModel terapiaModel;
    private TableModel medicamentoModel;
    
    //Cambios
    private Terapia_View_Add nuevaTerapiaUI = new Terapia_View_Add();
    private Medicamento_View_Add nuevoMedicamentoUI = new Medicamento_View_Add();
    
    private Map<Integer, TerapiaDiscapacidad> terapiasTabla = 
            new HashMap<Integer, TerapiaDiscapacidad>();
    
    private Set<TerapiaDiscapacidad> terapiasCalif = 
            new HashSet<TerapiaDiscapacidad>();
    private Set<MedicamentoDiscapacidad> medicamCalif = 
            new HashSet<MedicamentoDiscapacidad>();
    
    
    private Map<Integer, MedicamentoDiscapacidad> medicamentosTabla =
            new HashMap<Integer, MedicamentoDiscapacidad>();
    
    
    private constructor c;
    
    private String[] columnValoracion = {"Tipo", "Nombre", "Calificación", 
        "Suspendido", "Finalizado"};
    
    private String idCitas;
    
    private Map<DiscapacidadTratamiento, SetTerapiasMedicamentos> nuevosElemen = 
            new HashMap<DiscapacidadTratamiento, SetTerapiasMedicamentos>();
    
    private boolean guardado = false;
    
    /** Creates new form Evaluacion_View_Add */
    public Evaluacion_View_Add(Integer idPaciente, String nombPaciente, 
            String cedPac, constructor c, String idCitas) {
        initComponents();
        
        this.idPaciente = idPaciente;
        this.c = c;
        this.idCitas = idCitas;
        configComponentes(nombPaciente, cedPac);
        setTerapiaModel(new HashSet<TerapiaDiscapacidad>());
        
        c.setLabelModulo("Valoración");
        c.setLabelAccion("Evolución Paciente");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tratGroup = new javax.swing.ButtonGroup();
        calGroup = new javax.swing.ButtonGroup();
        suspenderGroup = new javax.swing.ButtonGroup();
        datosPacientePanel = new javax.swing.JPanel();
        jXTitledSeparator3 = new org.jdesktop.swingx.JXTitledSeparator();
        jLabel5 = new javax.swing.JLabel();
        nombresPaciente = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        identificacionPaciente = new javax.swing.JTextField();
        fechaPanel = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        fecha_evaluacion = new org.jdesktop.swingx.JXDatePicker();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        discapacidades = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaActuales = new org.jdesktop.swingx.JXTable();
        terapiaRadio = new javax.swing.JRadioButton();
        medicamentosRadio = new javax.swing.JRadioButton();
        jPanel3 = new javax.swing.JPanel();
        estableRadio = new javax.swing.JRadioButton();
        desfavorableRadio = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        satisfactorioRadio = new javax.swing.JRadioButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        siRadio = new javax.swing.JRadioButton();
        finalizarRadio = new javax.swing.JRadioButton();
        noRadio = new javax.swing.JRadioButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        tObservaVal = new javax.swing.JTextArea();
        jLabel8 = new javax.swing.JLabel();
        bAgregarEval = new javax.swing.JButton();
        bNuevosElem = new javax.swing.JButton();
        cEvaluacion = new javax.swing.JCheckBox();
        diagnosticoPanel = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        observaText = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane5 = new javax.swing.JScrollPane();
        tablaValorados = new org.jdesktop.swingx.JXTable();
        jLabel9 = new javax.swing.JLabel();
        bRemoverCalif = new javax.swing.JButton();
        guardarButton = new javax.swing.JButton();

        jXTitledSeparator3.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
        jXTitledSeparator3.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
        jXTitledSeparator3.setTitle("Datos Paciente");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("Nombres");

        nombresPaciente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel6.setText("Identificación");

        identificacionPaciente.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        javax.swing.GroupLayout datosPacientePanelLayout = new javax.swing.GroupLayout(datosPacientePanel);
        datosPacientePanel.setLayout(datosPacientePanelLayout);
        datosPacientePanelLayout.setHorizontalGroup(
            datosPacientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(datosPacientePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(datosPacientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jXTitledSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(datosPacientePanelLayout.createSequentialGroup()
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)
                        .addComponent(nombresPaciente, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(33, 33, 33)
                        .addComponent(identificacionPaciente, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        datosPacientePanelLayout.setVerticalGroup(
            datosPacientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(datosPacientePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jXTitledSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(datosPacientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(datosPacientePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(nombresPaciente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel6))
                    .addComponent(identificacionPaciente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel7.setText("Fecha:");

        fecha_evaluacion.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        fecha_evaluacion.setFormats("dd-MM-yyyy");

        javax.swing.GroupLayout fechaPanelLayout = new javax.swing.GroupLayout(fechaPanel);
        fechaPanel.setLayout(fechaPanelLayout);
        fechaPanelLayout.setHorizontalGroup(
            fechaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(fechaPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(fechaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(fecha_evaluacion, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                    .addComponent(jLabel7))
                .addContainerGap())
        );
        fechaPanelLayout.setVerticalGroup(
            fechaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, fechaPanelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fecha_evaluacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        discapacidades.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        discapacidades.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                discapacidadesValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(discapacidades);

        jLabel1.setText("Discapacidad tratamiento:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addContainerGap(97, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tablaActuales.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(tablaActuales);

        tratGroup.add(terapiaRadio);
        terapiaRadio.setSelected(true);
        terapiaRadio.setText("Terapias");
        terapiaRadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                terapiaRadioActionPerformed(evt);
            }
        });

        tratGroup.add(medicamentosRadio);
        medicamentosRadio.setText("Medicamentos");
        medicamentosRadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                medicamentosRadioActionPerformed(evt);
            }
        });

        calGroup.add(estableRadio);
        estableRadio.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        estableRadio.setSelected(true);
        estableRadio.setText("Estable");
        estableRadio.setForeground(java.awt.Color.blue);
        estableRadio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/estado_azul_select.png"))); // NOI18N
        estableRadio.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/estado_azul.png"))); // NOI18N

        calGroup.add(desfavorableRadio);
        desfavorableRadio.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        desfavorableRadio.setText("Desfavorable");
        desfavorableRadio.setForeground(java.awt.Color.red);
        desfavorableRadio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/estado_rojo_select.png"))); // NOI18N
        desfavorableRadio.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/estado_rojo.png"))); // NOI18N
        desfavorableRadio.setVerifyInputWhenFocusTarget(false);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Calificar evaluación:");

        calGroup.add(satisfactorioRadio);
        satisfactorioRadio.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        satisfactorioRadio.setText("Satisfactoria");
        satisfactorioRadio.setContentAreaFilled(false);
        satisfactorioRadio.setForeground(new java.awt.Color(66, 136, 2));
        satisfactorioRadio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/estado_verde_select.png"))); // NOI18N
        satisfactorioRadio.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/estado_verde.png"))); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(desfavorableRadio)
                .addGap(18, 18, 18)
                .addComponent(estableRadio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(satisfactorioRadio)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(desfavorableRadio)
                    .addComponent(estableRadio)
                    .addComponent(satisfactorioRadio))
                .addContainerGap())
        );

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setText("Suspender:");

        suspenderGroup.add(siRadio);
        siRadio.setText("Si");

        suspenderGroup.add(finalizarRadio);
        finalizarRadio.setText("Finalizar uso");

        suspenderGroup.add(noRadio);
        noRadio.setSelected(true);
        noRadio.setText("No");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addComponent(siRadio)
                .addGap(18, 18, 18)
                .addComponent(noRadio)
                .addGap(18, 18, 18)
                .addComponent(finalizarRadio)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(siRadio)
                    .addComponent(noRadio)
                    .addComponent(finalizarRadio))
                .addContainerGap())
        );

        tObservaVal.setColumns(20);
        tObservaVal.setLineWrap(true);
        tObservaVal.setRows(5);
        jScrollPane4.setViewportView(tObservaVal);

        jLabel8.setText("Observación:");

        bAgregarEval.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/add24.png"))); // NOI18N
        bAgregarEval.setText("Agregar Evaluación");
        bAgregarEval.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAgregarEvalActionPerformed(evt);
            }
        });

        bNuevosElem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/add24.png"))); // NOI18N
        bNuevosElem.setText("Agregar Terapia/Medicamento");
        bNuevosElem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bNuevosElemActionPerformed(evt);
            }
        });

        cEvaluacion.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cEvaluacion.setText("Usar evaluación para agregar medicamento/terapia");
        cEvaluacion.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                cEvaluacionStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(bAgregarEval)
                        .addGap(293, 293, 293))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2))
                        .addContainerGap())
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(terapiaRadio)
                                .addGap(18, 18, 18)
                                .addComponent(medicamentosRadio)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(bNuevosElem)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cEvaluacion)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(terapiaRadio)
                                .addComponent(medicamentosRadio))
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(bNuevosElem)
                                .addComponent(cEvaluacion)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(5, 5, 5))
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(bAgregarEval)
                .addContainerGap())
        );

        observaText.setColumns(20);
        observaText.setLineWrap(true);
        observaText.setRows(5);
        jScrollPane3.setViewportView(observaText);

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel4.setText("Observaciones generales:");

        tablaValorados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane5.setViewportView(tablaValorados);

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel9.setText("Evaluaciones generadas:");

        bRemoverCalif.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        bRemoverCalif.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/remove24.png"))); // NOI18N
        bRemoverCalif.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bRemoverCalifActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout diagnosticoPanelLayout = new javax.swing.GroupLayout(diagnosticoPanel);
        diagnosticoPanel.setLayout(diagnosticoPanelLayout);
        diagnosticoPanelLayout.setHorizontalGroup(
            diagnosticoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(diagnosticoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(diagnosticoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(diagnosticoPanelLayout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addGap(18, 18, 18)
                        .addComponent(bRemoverCalif))
                    .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 573, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(diagnosticoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3)
                    .addGroup(diagnosticoPanelLayout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        diagnosticoPanelLayout.setVerticalGroup(
            diagnosticoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(diagnosticoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(diagnosticoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(diagnosticoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel9)
                        .addComponent(bRemoverCalif))
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(diagnosticoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        guardarButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        guardarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/guardar32.png"))); // NOI18N
        guardarButton.setText("Guardar valoración");
        guardarButton.setEnabled(false);
        guardarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(datosPacientePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(fechaPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(diagnosticoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(guardarButton)
                .addGap(388, 388, 388))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(datosPacientePanel, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fechaPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(diagnosticoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(guardarButton)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

private void discapacidadesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_discapacidadesValueChanged

    terapiaRadio.setSelected(true);
    seleccionadoTerapias();
    
}//GEN-LAST:event_discapacidadesValueChanged

private void terapiaRadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_terapiaRadioActionPerformed

    System.out.println("Terapia radio selec");
    seleccionadoTerapias();
}//GEN-LAST:event_terapiaRadioActionPerformed

private void medicamentosRadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_medicamentosRadioActionPerformed

//    int index = discapacidades.getSelectedIndex();
//    if (index >= 0) {
//        DiscapacidadTratamiento discapacidad =
//                (DiscapacidadTratamiento) discModel.get(index);
////        setMedicamentosModel(discapacidad.getMedicamentosDiscapacidad());
//        setMedicamentosModel(MedicamentoDiscapacidadDAO.getMedicamentosActivos(discapacidad));
//    }
    System.out.println("Medicamento radio selec");
    seleccionadoMedicamentos();
}//GEN-LAST:event_medicamentosRadioActionPerformed

private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
   try{
       if(!terapiasCalif.isEmpty() || !medicamCalif.isEmpty()){
           for (TerapiaDiscapacidad terapia : terapiasCalif) {
               EvolucionTerapia evolucion = terapia.getEvolucion();
               if (evolucion.getSuspendido()) {
                   terapia.setEstado(TerapiaDiscapacidad.Estado.SUSPENDIDO);
                   TerapiaDiscapacidadDAO.actualizarEstadoItem(terapia);
               } else if (evolucion.getFinalizado()) {
                   terapia.setEstado(TerapiaDiscapacidad.Estado.FINALIZADO);
                   TerapiaDiscapacidadDAO.actualizarEstadoItem(terapia);
               }
               EvolucionTerapiaDAO.guardarEvolucion(evolucion);
           }
           for (MedicamentoDiscapacidad medicamento : medicamCalif) {
               EvolucionMedicamento evolucion = medicamento.getEvolucion();
               if (evolucion.getSuspendido()) {
                   medicamento.setEstado(MedicamentoDiscapacidad.Estado.SUSPENDIDO);
                   MedicamentoDiscapacidadDAO.actualizarEstadoItem(medicamento);
               } else if (evolucion.getFinalizar()) {
                   medicamento.setEstado(MedicamentoDiscapacidad.Estado.FINALIZADO);
                   MedicamentoDiscapacidadDAO.actualizarEstadoItem(medicamento);
               }
               EvolucionMedicamentoDAO.guardarEvolucion(evolucion);
           }
           tratamiento.setFechaEvaluacion(fecha_evaluacion.getDate());
           tratamiento.setNota(observaText.getText());
           TratamientoDAO.actualizarSoloTratamiento(tratamiento);

       }
       if(!nuevosElemen.isEmpty()){
           for (DiscapacidadTratamiento disc :
                   nuevosElemen.keySet()) {
               SetTerapiasMedicamentos setTerMed = nuevosElemen.get(disc);
               DiscapacidadTratamientoDAO.guardarNuevosElementos(disc, setTerMed);
           }
       }
       CitaDAO.cambiarEstadoCitaAsistido(idCitas);
       c.informarUsuario("ok[Inserción de evaluación]  Se guardo "
                   + "correctamente la información");
       guardarButton.setEnabled(false);
       guardado = true;
    }catch (Exception ex) {
            ex.printStackTrace();
            c.informarUsuario(String.format(
                    "error[No se pudo guardar evaluación] %s", ex.getMessage()));
        }
}//GEN-LAST:event_guardarButtonActionPerformed

private void bAgregarEvalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAgregarEvalActionPerformed
    int fila = tablaActuales.getSelectedRow();
    if (fila > -1) {
        System.out.println("Fila: " + fila);
        calificacion(fila);
        
//                    guardarButton.setEnabled(true);
    }
}//GEN-LAST:event_bAgregarEvalActionPerformed

private void bRemoverCalifActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRemoverCalifActionPerformed
        int selectedRow = tablaValorados.getSelectedRow();
        if(selectedRow > -1){
            TerapiaDiscapacidad terapia = terapiasTabla.get(selectedRow);
            if(null != terapia){
                terapiasCalif.remove(terapia);
                DefaultTableModel model = 
                        (DefaultTableModel)tablaValorados.getModel();
                model.removeRow(selectedRow);
            }
            MedicamentoDiscapacidad medicamento = medicamentosTabla.get(selectedRow);
            if(null != medicamento){
                medicamCalif.remove(medicamento);
                DefaultTableModel model = 
                        (DefaultTableModel)tablaValorados.getModel();
                model.removeRow(selectedRow);
            }
            actualizarAGeneradas(null, null);
            if(terapiaRadio.isSelected())
                terapiaRadioActionPerformed(null);
            else{
                medicamentosRadioActionPerformed(null);
            }
        }
}//GEN-LAST:event_bRemoverCalifActionPerformed

private void bNuevosElemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bNuevosElemActionPerformed
// TODO add your handling code here:
    int index = discapacidades.getSelectedIndex();
    if (index >= 0){
        DiscapacidadTratamiento discapacidad =
                (DiscapacidadTratamiento) discModel.get(index);
            //            setTerapiaModel(TerapiaDiscapacidadDAO.getTerapiasActivas(discapacidad));
            SetTerapiasMedicamentos nuevoElemento = nuevosElemen.get(discapacidad);
            if(null == nuevoElemento){
                nuevoElemento = new SetTerapiasMedicamentos();
                nuevosElemen.put(discapacidad, nuevoElemento);
            }
            VentanaNuevosElementos ventanaAdicion = new VentanaNuevosElementos(c, nuevoElemento ,"Asignar Nuevos Medicamentos / Terapias a Paciente");
            ventanaAdicion.setVisible(true);
            
            if(nuevoElemento.nuevasTer.isEmpty() && nuevoElemento.nuevosMedic.isEmpty()){
                nuevosElemen.remove(discapacidad);
            }
            verificarGuardarEvaluacion();
    }
}//GEN-LAST:event_bNuevosElemActionPerformed

private void cEvaluacionStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_cEvaluacionStateChanged
    verificarGuardarEvaluacion();
}//GEN-LAST:event_cEvaluacionStateChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAgregarEval;
    private javax.swing.JButton bNuevosElem;
    private javax.swing.JButton bRemoverCalif;
    private javax.swing.JCheckBox cEvaluacion;
    private javax.swing.ButtonGroup calGroup;
    private javax.swing.JPanel datosPacientePanel;
    private javax.swing.JRadioButton desfavorableRadio;
    private javax.swing.JPanel diagnosticoPanel;
    private javax.swing.JList discapacidades;
    private javax.swing.JRadioButton estableRadio;
    private javax.swing.JPanel fechaPanel;
    private org.jdesktop.swingx.JXDatePicker fecha_evaluacion;
    private javax.swing.JRadioButton finalizarRadio;
    private javax.swing.JButton guardarButton;
    private javax.swing.JTextField identificacionPaciente;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private org.jdesktop.swingx.JXTitledSeparator jXTitledSeparator3;
    private javax.swing.JRadioButton medicamentosRadio;
    private javax.swing.JRadioButton noRadio;
    private javax.swing.JTextField nombresPaciente;
    private javax.swing.JTextArea observaText;
    private javax.swing.JRadioButton satisfactorioRadio;
    private javax.swing.JRadioButton siRadio;
    private javax.swing.ButtonGroup suspenderGroup;
    private javax.swing.JTextArea tObservaVal;
    private org.jdesktop.swingx.JXTable tablaActuales;
    private org.jdesktop.swingx.JXTable tablaValorados;
    private javax.swing.JRadioButton terapiaRadio;
    private javax.swing.ButtonGroup tratGroup;
    // End of variables declaration//GEN-END:variables

    private void seleccionadoTerapias(){
        int index = discapacidades.getSelectedIndex();
        if (index >= 0) {
            DiscapacidadTratamiento discapacidad =
                    (DiscapacidadTratamiento) discModel.get(index);
            //            setTerapiaModel(TerapiaDiscapacidadDAO.getTerapiasActivas(discapacidad));
            setTerapiaModel(filtrarTerapias(discapacidad.getTerapiasDiscapacidad()));
            reiniciarCalif();
        }
                
//        for(ActionListener actionListener : bAgregarNuevo.getActionListeners()){
//            bAgregarNuevo.removeActionListener(actionListener);
//        }
//        bAgregarNuevo.addActionListener(agregarNuevaTerapiaListener);
    }
    
    private void seleccionadoMedicamentos(){
        int index = discapacidades.getSelectedIndex();
        if (index >= 0) {
            DiscapacidadTratamiento discapacidad =
                    (DiscapacidadTratamiento) discModel.get(index);
            //            setTerapiaModel(TerapiaDiscapacidadDAO.getTerapiasActivas(discapacidad));
            
            
            setMedicamentosModel(filtrarMedicamentos(discapacidad.getMedicamentosDiscapacidad()));
            reiniciarCalif();
        }
        
//        for(ActionListener actionListener : bAgregarNuevo.getActionListeners()){
//            bAgregarNuevo.removeActionListener(actionListener);
//        }
//        bAgregarNuevo.addActionListener(agregarNuevoMedicListener);
    }
    
    private void configComponentes(String nombPaciente, String cedPac) {
        
        tratamiento = TratamientoDAO.getTratamiento(idPaciente);

        for (DiscapacidadTratamiento discapacidad : tratamiento.getDispacacidadTratamientos()) {
            discModel.addElement(discapacidad);
        }
        discapacidades.setModel(discModel);
        tablaActuales.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        tablaActuales.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                int fila = tablaActuales.rowAtPoint(e.getPoint());
                if (fila > -1) {
                    bAgregarEval.setEnabled(true);
                    reiniciarCalif();
                }else{
                    bAgregarEval.setEnabled(false);
                }
            }
        });
        
        this.nombresPaciente.setText(nombPaciente);
        this.identificacionPaciente.setText(cedPac);
        this.nombresPaciente.setEditable(false);
        this.identificacionPaciente.setEditable(false);
        fecha_evaluacion.setDate(new Date());
        fecha_evaluacion.setEditable(false);//Enabled(false);
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        JFormattedTextField dateEditor = new JFormattedTextField(df);
        fecha_evaluacion.setEditor(dateEditor);
        String nota = tratamiento.getNota();
        observaText.setText(null != nota? nota: "");
        
        
        
        DefaultTableModel valoradosModel = new DefaultTableModel(null, columnValoracion);
        tablaValorados.setModel(valoradosModel);
    }
    
    private void setTerapiaModel(Set<TerapiaDiscapacidad> terapias) {
        int size = terapias.size();
        Object[][] datos = new Object[size][columnTerapia.length];

        TerapiaDiscapacidad[] toArray = terapias.toArray(new TerapiaDiscapacidad[size]);
        mapTerapias = new HashMap<Integer, TerapiaDiscapacidad>();
        for (int i = 0; i < toArray.length; i++) {
            datos[i][0] = toArray[i].getIdTerapia();//.toString();
            datos[i][1] = cbx.getValueTerapia(toArray[i].getIdTerapia().toString());
            
            mapTerapias.put(i, toArray[i]);
            
            System.out.println("Terapia: " + toArray[i].getIdTerapia().toString());
            datos[i][2] = String.format("Cada %s %s", toArray[i].getIntensidad(), 
                    cbx.getValueMedidas(toArray[i].getIntensidadMedidaTiempo().toString()));
//            datos[i][3] = cbx.getValueMedidas(toArray[i].getIntensidadMedidaTiempo().toString());
            System.out.println("Intensidad medida: " + toArray[i].getIntensidadMedidaTiempo().toString());
            datos[i][3] = toArray[i].getCantidad();
            datos[i][4] = toArray[i].getFechaInicio();
        }

        terapiaModel = new DefaultTableModel(datos, columnTerapia);
        
//        terapiaModel.addTableModelListener();
        
        tablaActuales.setModel(terapiaModel);
    }

    private void setMedicamentosModel(Set<MedicamentoDiscapacidad> medicamentos) {
        int size = medicamentos.size();
        Object[][] datos = new Object[size][columnMedic.length];

        MedicamentoDiscapacidad[] toArray = medicamentos.toArray(
                new MedicamentoDiscapacidad[size]);
//private String[] columnMedic = {"Id","Medicamento", "Dosis", "Medida", "Uso", "Medida", "Inicio"};
        for (int i = 0; i < toArray.length; i++) {
            datos[i][0] = toArray[i].getIdMedicamento();//.toString());
            datos[i][1] = cbx.getValueMedicamentos(toArray[i].getIdMedicamento().toString());

            mapMedicamentos.put(i, toArray[i]);

            System.out.println("Medicamentos: " + toArray[i].getIdMedicamento().toString());
            
            datos[i][2] = String.format("Cada %s %s", toArray[i].getDosis(),
                    cbx.getValueMedidas(toArray[i].getUsoMedidaTiempo().toString()));
//            datos[i][3] = cbx.getValueMedidas(toArray[i].getUsoMedidaTiempo().toString());
            datos[i][3] = String.format("Cada %s %s", toArray[i].getUso(),
                    cbx.getValueMedidas(toArray[i].getUsoMedidaTiempo().toString()));
//            datos[i][4] = cbx.getValueMedidas(toArray[i].getUsoMedidaTiempo().toString());
            datos[i][4] = toArray[i].getFechaInicio();
        }

        medicamentoModel = new DefaultTableModel(datos, columnMedic);
        tablaActuales.setModel(medicamentoModel);
    }

    private void calificacion(Integer val){
//        Integer val = Integer.valueOf(id.toString());
        if(terapiaRadio.isSelected()){
            TerapiaDiscapacidad terapia = mapTerapias.get(val);
            
            EvolucionTerapia evolTerapia = new EvolucionTerapia();
            evolTerapia.setTerapiaDiscapacidad(terapia);
            
            evolTerapia.setCalificacion(calificacionCombos());
            evolTerapia.setFechaControl(fecha_evaluacion.getDate());
            evolTerapia.setObservacion(tObservaVal.getText());
            evolTerapia.setSuspendido(siRadio.isSelected());
            evolTerapia.setFinalizado(finalizarRadio.isSelected());
            
            terapia.setEvolucion(evolTerapia);
            actualizarAGeneradas(terapia, null);
            terapiaRadioActionPerformed(null);
            
        }else{
            MedicamentoDiscapacidad medicamento = mapMedicamentos.get(val);
            EvolucionMedicamento evolMedicamento = new EvolucionMedicamento();
            evolMedicamento.setMedicamentoDiscapacidad(medicamento);
            evolMedicamento.setCalificacion(calificacionCombos());
            evolMedicamento.setFechaControl(fecha_evaluacion.getDate());
            evolMedicamento.setObservacion(observaText.getText());
            evolMedicamento.setSuspendido(siRadio.isSelected());
            evolMedicamento.setFinalizar(finalizarRadio.isSelected());
            
            medicamento.setEvolucion(evolMedicamento);
            actualizarAGeneradas(null, medicamento);
            medicamentosRadioActionPerformed(null);
        }
    }

    private Integer calificacionCombos() {
        if(desfavorableRadio.isSelected())
            return 0;
        else if(estableRadio.isSelected())
            return 1;
        else 
            return 2;
    }
    
    private void reiniciarCalif(){
        desfavorableRadio.setSelected(true);
        noRadio.setSelected(true);
        tObservaVal.setText("");
    }

    private void actualizarAGeneradas(TerapiaDiscapacidad terapia, 
            MedicamentoDiscapacidad medicamento) {
        
        if(null != terapia){
            terapiasCalif.add(terapia);
        }
        if(null != medicamento){
            medicamCalif.add(medicamento);
        }
        
        int size = terapiasCalif.size() + medicamCalif.size();
        Object[][] datos = new Object[size][columnValoracion.length];

        terapiasTabla = new HashMap<Integer, TerapiaDiscapacidad>();
        TerapiaDiscapacidad[] arrayTerapias =
                terapiasCalif.toArray(new TerapiaDiscapacidad[terapiasCalif.size()]);
        
        for (int i = 0; i < arrayTerapias.length; i++) {
            final TerapiaDiscapacidad terapiaAct = arrayTerapias[i];
            terapiasTabla.put(i, terapiaAct);
//            private String[] columnValoracion = {"Tipo", "Nombre", "Calificación", 
//        "Suspendido", "Finalizado"};
            datos[i][0] = "Terapia";
            datos[i][1] = terapiaAct.getTerapia();
            datos[i][2] = terapiaAct.getEvolucion().getCalificacion();
            datos[i][3] = terapiaAct.getEvolucion().getSuspendido() ? "Si": "No";
            datos[i][4] = terapiaAct.getEvolucion().getFinalizado() ? "Si": "No";
        }
        
        medicamentosTabla = new HashMap<Integer, MedicamentoDiscapacidad>();
        MedicamentoDiscapacidad[] arrayMedic = medicamCalif.toArray(
                new MedicamentoDiscapacidad[medicamCalif.size()]);
        
        for(int i = 0; i < arrayMedic.length; i++){
            MedicamentoDiscapacidad medicAct = arrayMedic[i];
            int index = terapiasCalif.size() + i;
            
            medicamentosTabla.put(index, medicAct);
            datos[index][0] = "Medicamento";
            datos[index][1] = medicAct.getMedicamento();
            datos[index][2] = medicAct.getEvolucion().getCalificacion();
            datos[index][3] = medicAct.getEvolucion().getSuspendido() ? "Si": "No";
            datos[index][4] = medicAct.getEvolucion().getFinalizar() ? "Si": "No";
        }
       DefaultTableModel valoradosModel = new DefaultTableModel(datos, columnValoracion);
       tablaValorados.setModel(valoradosModel);
       
//       guardarButton.setEnabled(size > 0);
       verificarGuardarEvaluacion();
    }
    
    private ActionListener agregarNuevaTerapiaListener = new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Terapia listener");
                try {
                    TerapiaDiscapacidad nueva = nuevaTerapiaUI.getInfo();
                    int index = discapacidades.getSelectedIndex();
                    if (index >= 0) {
                        Object dis = discModel.get(index);
                        DiscapacidadTratamiento trat = (DiscapacidadTratamiento) dis;
                        nueva.setDiscapacidadTratamiento(trat);
                        nueva.setFechaInicio(fecha_evaluacion.getDate());
                        
                        TerapiaDiscapacidadDAO.guardarItem(nueva);
                        trat.getTerapiasDiscapacidad().add(nueva);
                        
                        
                        setTerapiaModel(filtrarTerapias(trat.getTerapiasDiscapacidad()));
                        reiniciarCalif();
                        nuevaTerapiaUI.resetearComponentes();
                        c.informarUsuario("ok[Inserción de nueva terapia]  Se guardo "
                                + "correctamente la información");
                        
                    }
                } catch (Exception ex) {
                    c.informarUsuario(String.format(
                            "error[Error al agregar terapia] %s", ex.getMessage()));
                }
            }
        };
    
    private ActionListener agregarNuevoMedicListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("medicamento listener");
            try {
                MedicamentoDiscapacidad nueva = nuevoMedicamentoUI.getInfo();
                int index = discapacidades.getSelectedIndex();
                if (index >= 0) {
                    Object dis = discModel.get(index);
                    DiscapacidadTratamiento trat = (DiscapacidadTratamiento) dis;
                    nueva.setFechaInicio(fecha_evaluacion.getDate());
                    nueva.setDiscapacidadTratamiento(trat);
                    
                    MedicamentoDiscapacidadDAO.guardarItem(nueva);
                    trat.getMedicamentosDiscapacidad().add(nueva);
                    
                    setMedicamentosModel(filtrarMedicamentos(trat.getMedicamentosDiscapacidad()));
                    reiniciarCalif();
                    nuevoMedicamentoUI.resetearComponentes();
                    c.informarUsuario("ok[Inserción de nuevo medicamento]  Se guardo "
                            + "correctamente la información");
//                    vistasPanel.removeAll();
//                    botonAgregarTer.removeActionListener(agregarMedicamentoListener);
                }
            } catch (Exception ex) {
                c.informarUsuario(String.format(
                        "error[Error al agregar medicamento] %s", ex.getMessage()));
            }
        }
    };

    private Set<TerapiaDiscapacidad> filtrarTerapias(Set<TerapiaDiscapacidad> terapiasDiscapacidad) {
        Set<TerapiaDiscapacidad> terMostrar = new HashSet<TerapiaDiscapacidad>();
        for (TerapiaDiscapacidad actual : terapiasDiscapacidad) {
            if (!terapiasCalif.contains(actual)) {
                terMostrar.add(actual);
            }
        }
        return terMostrar;
    }

    private Set<MedicamentoDiscapacidad> filtrarMedicamentos(Set<MedicamentoDiscapacidad> medicamentosDiscapacidad) {
        Set<MedicamentoDiscapacidad> medMostrar = new HashSet<MedicamentoDiscapacidad>();
        for (MedicamentoDiscapacidad actual : medicamentosDiscapacidad) {
            if (!medicamCalif.contains(actual)) {
                medMostrar.add(actual);
            }
        }
        return medMostrar;
            
    }

    private void verificarGuardarEvaluacion() {
        guardarButton.setEnabled( !guardado && 
                ((!nuevosElemen.isEmpty() && cEvaluacion.isSelected())
                || !terapiasCalif.isEmpty() || !medicamCalif.isEmpty()));
    }
    
    public static class SetTerapiasMedicamentos{
        public Set<MedicamentoDiscapacidad> nuevosMedic = 
                new HashSet<MedicamentoDiscapacidad>();
        public Set<TerapiaDiscapacidad> nuevasTer = 
                new HashSet<TerapiaDiscapacidad>();
    }
}
